package Day7;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/ErrorHeader")
public class Error extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        Integer status_code=(Integer) req.getAttribute("javax.servlet.error.status_code");
        String  servlet_name=(String) req.getAttribute("javax.servlet.error.servlet_name");
        String  servlet_uri=(String) req.getAttribute("javax.servlet.error.servlet_uri");
        if(servlet_name==null){
            servlet_name="unkonwn";
        }
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(throwable==null){
            writer.println("异常信息丢失");
        }
        else if(status_code==null){
            writer.println("异常状态码丢失");
        }
        else {
            writer.println("发生异常的Sevlet"+servlet_name);
            writer.println("异常:"+throwable.getClass().getName());
            writer.println("异常信息:"+throwable.getMessage());
            writer.println("请求URI:"+servlet_uri);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}
